package com.bbx.demo.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.Charset;
import java.util.Scanner;

public class SocketClient {


    private String host = "192.168.2.252";
    private int port = 9099;


    public SocketClient() {
    }

    public static void main (String [] args) throws InterruptedException {
        SockerClientHandler sockerClientHandler = new SockerClientHandler();
        new SocketClient().start(sockerClientHandler);

    }
    public void start(ChannelHandler socketClientHandler) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8"))).addLast(socketClientHandler);
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
        Scanner scanner = new Scanner(System.in);
        while(true){
            String s = scanner.nextLine();
            if ("exit".equals(s)) {
                channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(s.getBytes(Charset.forName("utf-8")))).addListener(ChannelFutureListener.CLOSE);
            } else {
                channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(s.getBytes(Charset.forName("utf-8"))));
            }
        }
    }


}
